package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"manuscript-service/models/mysql"

	"manuscript-service/manurpc/internal/svc"
	"manuscript-service/manurpc/manurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ManuAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewManuAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManuAddLogic {
	return &ManuAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 稿件新增
func (l *ManuAddLogic) ManuAdd(in *manurpc.ManuAddRequest) (*manurpc.ManuAddResponse, error) {
	// todo: add your logic here and delete this line

	var findManu mysql.Manuscript

	begin := mysql.DB

	if err := findManu.FindManuByTitle(mysql.DB, in.Title); err == nil {
		begin.Rollback()
		return nil, errors.New("该商品已存在")
	}

	class := &mysql.Class{
		Name: in.ClassName,
	}

	if err := class.FindClassByName(mysql.DB, in.ClassName); err != nil {
		begin.Rollback()
		return nil, err
	}

	manu := &mysql.Manuscript{
		Model:   gorm.Model{},
		Title:   in.Title,
		Image:   in.Image,
		Like:    in.Like,
		ClassId: int64(class.ID),
	}

	if err := manu.ManuAdd(mysql.DB); err != nil {
		begin.Rollback()
		return nil, err
	}

	begin.Commit()

	return &manurpc.ManuAddResponse{
		ManuscriptId: int64(manu.ID),
	}, nil
}
